let publish = document.getElementsByClassName("publish")[0];
let textarea = document.getElementsByTagName("textarea")[0];
// let userIds = localStorage.getItem("userId");
publish.onclick = function () {
    if (!textarea.value) {
        alert("留言不能为空")
        return
    } else if (!userId) {
        alert("请登录以后在发表留言")
        textarea.value = "";
        return
    } else if (userId) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let data = JSON.parse(xhr.responseText);
                xr(data);
                textarea.value = "";
            }
        }
        xhr.open("GET",
            `/api/message/addMessage?AdminId=${userId}&userMessage=${textarea.value}&time=${getNowTime()}`,
            true)
        xhr.send()
    }
}
let down = document.getElementsByClassName("down")[0];

function xr(data) {
    down.innerHTML = ""
    for (let i =0; i < data.length; i++) {
        down.innerHTML += `
                <div class="message" id="${data[i].id}">
                    <img src="${data[i].Admin.userimg}" alt="">
                    <div>
                        <span>${data[i].Admin.userName}</span><span>${data[i].time}</span>
                        <div>${data[i].userMessage}</div>
                    </div>
                </div>`
    }
}
//获取当前时间
function getNowTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var time = year + '-' + addZero(month) + '-' + addZero(day) + ' ' + addZero(hour) + ':' + addZero(minute) +
        ':' + addZero(second);
    return time;
}

function addZero(s) {
    return s < 10 ? ('0' + s) : s;
}

let yhm = document.getElementsByClassName("yhm")[0];
let yhtx = document.getElementsByClassName("yhtx")[0];
let xinxi = document.getElementsByClassName("xinxi")[0];
//获取账号用户名
function Yhm() {
    if (userId) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let data = JSON.parse(xhr.responseText);
                xinxi.innerHTML =
                    `<img src="${data.userimg}" alt="" class="用户头像"><span class="yhm">${data.userName}</span>`
            }
        }
        xhr.open("GET", `/api/admin/getYhm?userID=${userId}`, true)
        xhr.send()
    }
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let data = JSON.parse(xhr.responseText);
            xr(data)
        }
    }
    xhr.open("GET", `/api/message/getYhly`, true)
    xhr.send()
}
Yhm()